package com.aiserver.filter;

import com.aiserver.wrapper.RepeatableReadHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求包装过滤器
 * 将HttpServletRequest包装为可重复读取的请求
 */
@Component
@Order(1) // 确保在其他过滤器之前执行
public class RequestWrapperFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(RequestWrapperFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            
            // 只对POST和PUT请求进行包装
            String method = httpRequest.getMethod();
            if ("POST".equals(method) || "PUT".equals(method)) {
                try {
                    // 包装请求为可重复读取的请求
                    RepeatableReadHttpServletRequest wrappedRequest = 
                        new RepeatableReadHttpServletRequest(httpRequest);
                    chain.doFilter(wrappedRequest, response);
                    return;
                } catch (Exception e) {
                    logger.error("包装请求失败", e);
                    // 如果包装失败，继续使用原始请求
                }
            }
        }
        
        // 对于其他请求或包装失败的情况，直接传递原始请求
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("RequestWrapperFilter 初始化完成");
    }

    @Override
    public void destroy() {
        logger.info("RequestWrapperFilter 销毁");
    }
}